import { computed, onBeforeMount, ref, inject, h } from 'vue';
import vueRouter from '@/router';
const message = window['$message'];
import { useUser } from '@/store/modules/user';
import { routerBack } from '@/utils';
import { NSelect, NButton } from 'naive-ui';
const userStore = useUser();

interface formOption {
  onInit?: Function; // 详情页面初始化
  onCreate?: Function; // 详情表单创建
  onUpdate?: Function; // 详情表单更新
  onStartFlowPath?: Function; // 详情表单开始流程
  onSubmit?: Function; // 详情表单提交
  onAfterAction?: Function; // 详情表单提交or保存后操作
  customReset?: Function; // 自定义重置操作
  submitFormReplaceRouter?: boolean; // 保存后是否刷新页面，跳转到对应的详情页面
}
export function useDetailForm(detail, option: formOption) {
  const flowPathUserId = ref('');
  const router = vueRouter;
  const route = vueRouter.currentRoute.value;
  const defaultFormValue = JSON.parse(JSON.stringify(detail.value));
  const formRef = ref<any>(null);
  const loading = ref<boolean>(false);
  // 页面地址传参是否可编辑
  const queryIsEdit = ref(1);
  // 表单是否可编辑
  const isEdit = computed(() => {
    // detailFormIsEdit 组件传参是否可编辑
    if (inject('detailFormIsEdit') === 0) {
      return 0;
    } else if (detail.value.processStatus && detail.value.processStatus !== 0) {
      return 0;
    } else {
      return queryIsEdit.value;
    }
  });
  const userInfo = userStore.getUserInfo;
  onBeforeMount(() => {
    queryIsEdit.value = Number(route.query?.isEdit ?? 1) as number;
    option.onInit && option.onInit(route);
  });
  const resetForm = () => {
    formRef.value.restoreValidation();
    detail.value = JSON.parse(JSON.stringify(defaultFormValue));
  };
  const submitForm = (value: any = null) => {
    formRef.value.validate(async (errors: boolean) => {
      if (!errors) {
        loading.value = true;
        try {
          if (value?.id) {
            if (option.onUpdate) {
              const r = await option.onUpdate(value);
              r && message.success('修改成功');
            }
          } else {
            if (option.onCreate) {
              const r = await option.onCreate(value);
              r && message.success('添加成功');
              if (option.submitFormReplaceRouter && option.submitFormReplaceRouter === true) {
                await router.replace({ name: route.name as string, params: { id: r } });
              }
            }
          }
          // if (!value?.id) {
          //   resetForm();
          // }
          option.onAfterAction && option.onAfterAction();
        } finally {
          loading.value = false;
        }
      } else {
        window['$message'].warning('表单验证不通过，请检查表单填写内容');
      }
    });
  };

  const submitSaveForm = async (value: any) => {
    formRef.value.validate(async (errors: boolean) => {
      if (!errors) {
        loading.value = true;
        const dialogLoading = ref(false);
        try {
          window['$dialog'].info({
            title: '提示',
            content: `确定提交吗?`,
            loading: dialogLoading,
            positiveText: '确定',
            negativeText: '取消',
            onPositiveClick: async () => {
              dialogLoading.value = true;
              if (value?.id) {
                if (option.onUpdate) {
                  const r = await option.onUpdate(value);
                  r && message.success('修改成功');
                }
              } else {
                if (option.onCreate) {
                  const r = await option.onCreate(value);
                  r && message.success('添加成功');
                  value.id = r;
                }
              }
              const res =
                option.onStartFlowPath &&
                (await option.onStartFlowPath({
                  id: value.id,
                }));
              dialogLoading.value = false;
              if (res.list && res.list.length > 1) {
                const flowDialog = window['$dialog'].info({
                  title: '选择下次流程审批人',
                  loading: dialogLoading,
                  content: () => {
                    return h(NSelect, {
                      onUpdateValue: (e) => {
                        flowPathUserId.value = e;
                      },
                      placeholder: '请选择审批人',
                      options: res.list,
                      valueField: 'id',
                      labelField: 'name',
                    });
                  },
                  action: () => {
                    return h(
                      NButton,
                      {
                        type: 'primary',
                        size: 'small',
                        loading: dialogLoading.value,
                        onClick: async () => {
                          dialogLoading.value = true;
                          option.onSubmit &&
                            (await option.onSubmit({
                              id: value.id,
                              taskKey: res.taskKey,
                              userId: flowPathUserId.value,
                            }));
                          window['$message'].success('提交成功');
                          flowDialog.destroy();
                          dialogLoading.value = false;
                          routerBack();
                        },
                      },
                      '确定提交'
                    );
                  },
                });
              } else {
                option.onSubmit &&
                  (await option.onSubmit({
                    id: value.id,
                  }));
                window['$message'].success('提交成功');
                routerBack();
              }
            },
          });
        } finally {
          loading.value = false;
        }
      } else {
        window['$message'].warning('表单验证不通过，请检查表单填写内容');
      }
    });
  };
  return {
    formRef,
    loading,
    resetForm,
    submitForm,
    submitSaveForm,
    isEdit,
    userInfo,
    route,
  };
}
